import { isNullOrUndef } from '@/utils/is';
import { getToken } from '@/utils/token';
import axios from 'axios';
import { toLogin } from '@/router';

export function reqResolve(config) {
    // 防止缓存，给get请求加上时间戳
    if (config.method === 'get')
        config.params = { ...config.params, _timestamp: new Date().getTime() };

    // 处理不需要token的请求
    if (config.withoutToken)
        return config;

    const token = getToken();

    if (!token) {
        toLogin();
        return Promise.reject({ code: '-1', message: '未登录' });
    }

    config.headers.Authorization = config.headers.Authorization || token;

    return config;
}

export function reqReject(error) {
    return Promise.reject(error);
}

export function respResolve(response) {
    return response?.data
}

export function respReject(error) {
    if (error.response)
        error = error.response.data;

    let { code, message } = error || {};

    console.log(error);

    if (isNullOrUndef(code)) {
        // 未知错误
        code = -1;
        message = '接口异常！';
    } else {
        /**
         * TODO 此处可以根据后端返回的错误码自定义框架层面的错误处理
         */
        switch (code) {
            case 401:
                message = message || '登录已过期';
                break;
            case 403:
                message = message || '没有权限';
                break;
            case 404:
                message = message || '资源或接口不存在';
                break;
            default:
                message = message || '未知异常';
                break;
        }
    }

    console.error(`【${code}】 ${error}, ${message}`);

    $message.error(message);

    return Promise.reject({ code, message, error });
}

export function createAxios(options = {}) {

    const defaultOptions = {
        baseURL: import.meta.env.VITE_API_BASE_PATH,
        timeout: 10000,
    };

    const service = axios.create({
        ...defaultOptions,
        ...options,
    });

    service.interceptors.request.use(reqResolve, reqReject);
    service.interceptors.response.use(respResolve, respReject);

    return service;
}

export const defaultAxios = createAxios();

export async function request(config = {}) {
    const resp = await defaultAxios(config);
    return resp;
}